<template>
  <div id="addSpacePage">
    <h2 style="margin-bottom: 16px">
      {{ route.query?.id ? '修改 ' : '创建 ' }}{{ SPACE_TYPE_MAP[spaceType] }}
    </h2>

    <!-- 空间信息表单 -->
    <a-form
      layout="vertical"
      ref="formRef"
      name="spaceForm"
      :model="spaceForm"
      @finish="handleSubmit"
    >
      <a-form-item name="spaceName" label="空间名称">
        <a-input v-model:value="spaceForm.spaceName" placeholder="请输入空间名称" allowClear />
      </a-form-item>
      <a-form-item name="spaceLevel" label="空间级别">
        <a-select
          v-model:value="spaceForm.spaceLevel"
          placeholder="请选择空间级别"
          :options="SPACE_LEVEL_OPTIONS"
          allowClear
          style="min-width: 180px"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%" :loading="submitting">
          {{ route.query?.id ? '修改' : '创建' }}
        </a-button>
      </a-form-item>
    </a-form>

    <a-card title="空间级别介绍">
      <a-typography-paragraph>
        * 目前仅支持开通普通版，如需升级空间，请联系
        <a href="https://gitee.com/kkwwk/w-picture" target="_blank">w</a>。
      </a-typography-paragraph>
      <a-typography-paragraph v-for="spaceLevel in spaceLevelList">
        {{ spaceLevel.text }}： 大小 {{ formatSize(spaceLevel.maxSize) }}， 数量
        {{ spaceLevel.maxCount }}
      </a-typography-paragraph>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {
  SPACE_LEVEL_ENUM,
  SPACE_LEVEL_OPTIONS,
  SPACE_TYPE_ENUM,
  SPACE_TYPE_MAP,
} from '@/constants/space.ts'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  addSpaceUsingPost,
  editSpaceUsingPost,
  getSpaceVoByIdUsingGet,
  listSpaceLevelUsingGet,
} from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import { formatSize } from '../../utils'

// 表单数据模型
const spaceForm = reactive<API.SpaceAddRequest | API.SpaceUpdateRequest>({
  spaceName: '',
  spaceLevel: SPACE_LEVEL_ENUM.COMMON,
})

// 获取路由和路由器实例
const router = useRouter()
const route = useRoute()

// 空间类别
const spaceType = computed(() => {
  // 如果路由中存在type参数，则使用其值作为空间类别，否则使用默认值
  if (route.query?.type) {
    return Number(route.query.type)
  }
  // 默认为私有空间
  return SPACE_TYPE_ENUM.PRIVATE
})

// 提交状态标记
const submitting = ref(false)

// 处理表单提交逻辑。
const handleSubmit = async (values) => {
  console.log('handleSubmit', values)
  // debugger
  if (submitting.value) return
  submitting.value = true
  try {
    let res
    const spaceId = oldSpace.value?.id

    if (spaceId) {
      // 更新
      res = await editSpaceUsingPost({
        id: spaceId,
        ...spaceForm,
      })
    } else {
      // 创建
      res = await addSpaceUsingPost({
        ...spaceForm,
        spaceType: spaceType.value,
      })
    }

    console.log('res', res)
    if (res.code === 0 && res.data) {
      message.success(`${spaceId ? '修改' : '创建'}成功`)
      // 跳转到详情页
      let path = `/space/${spaceId ?? res.data}`
      await router.push({
        path,
      })
    } else {
      message.error(`失败: ${res.message || '未知错误'}`)
    }
  } catch (error) {
    message.error('提交失败')
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

const spaceLevelList = ref<API.SpaceLevel[]>([])

// 获取空间级别
const fetchSpaceLevelList = async () => {
  const res = await listSpaceLevelUsingGet()
  if (res.code === 0 && res.data) {
    spaceLevelList.value = res.data
  } else {
    message.error('加载空间级别失败，' + res.data.message)
  }
}

onMounted(() => {
  fetchSpaceLevelList()
})

const oldSpace = ref<API.SpaceVO>()

// 获取老数据
const getOldSpace = async () => {
  // 获取数据
  const id = route.query?.id
  if (id) {
    const res = await getSpaceVoByIdUsingGet({
      id: id,
    })
    if (res.code === 0 && res.data) {
      const data = res.data
      oldSpace.value = data
      spaceForm.spaceName = data.spaceName
      spaceForm.spaceLevel = data.spaceLevel
    }
  }
}

// 页面加载时，请求老数据
onMounted(() => {
  getOldSpace()
})
</script>

<style scoped></style>
